package com.yy.watchmen.utils

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager

abstract class BaseFloatWindowManager {

    private var mWindowManager: WindowManager? = null

    private var mLayoutParams: WindowManager.LayoutParams? = null

    private var mFloatView: View? = null
    private fun initWindowManager(context: Context) {
        if (mWindowManager == null) {
            //Activity中的方法,得到窗口管理器
            mWindowManager =
                context.getSystemService(AccessibilityService.WINDOW_SERVICE) as WindowManager
            mLayoutParams = WindowManager.LayoutParams().apply {
                // 设置窗体显示类型
                type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                } else {
                    WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
                }
                format = PixelFormat.TRANSLUCENT
                flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                gravity = Gravity.CENTER_VERTICAL or Gravity.RIGHT
                width = WindowManager.LayoutParams.WRAP_CONTENT
                height = WindowManager.LayoutParams.WRAP_CONTENT
            }
        }
    }

    private fun initFloatView(context: Context) {
        if (mFloatView == null) {
            mFloatView = LayoutInflater.from(context).inflate(provideFloatView(), null)
            mFloatView?.let {

                initView(it)
            }
        }
    }

    fun show(context: Context) {
        initWindowManager(context)
        initFloatView(context)
        if (mFloatView?.parent == null) {
            mWindowManager?.addView(mFloatView, mLayoutParams)
        }
    }

    fun remove() {
        mFloatView?.parent?.let {
            mWindowManager?.removeView(mFloatView)
        }

    }

    abstract fun provideFloatView(): Int

    abstract fun initView(floatView: View)

    fun <T : View> findViewById(id: Int): T? {
        return mFloatView?.findViewById(id)
    }
}